<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应式</title>
</head>

<body>
    <script>
        // 下面三者是一种树形结构
        // target 代理对象的原始对象 (weakMap)
        //     key 被读取的字段名 (Map)
        //       effectFn 副作用函数 (Set)

        let bucket = new WeakMap()

        let activeEffect

        function effect(effectFn) {
            activeEffect = effectFn
            effectFn()
        }

        function track(target, key) {
            if (!activeEffect) return
            let map = bucket.get(target)
            if (!map) {
                map = new Map()
                bucket.set(target, map)
            }
            let set = map.get(key)
            if (!set) {
                set = new Set()
                map.set(key, set)
            }
            set.add(activeEffect)
        }

        function trigger(target, key) {
            const map = bucket.get(target)
            if (!map) return
            const set = map.get(key)
            if (!set) return
            set.forEach(fn => fn())
        }

        const data = {
            text: '123'
        }

        const obj = new Proxy(data, {
            get(target, key) {
                track(target, key)
                return target[key]
            },
            set(target, key, value) {
                target[key] = value
                trigger(target, key)
            }
        })

        effect(() => {
            console.log(obj.text)
        })

        setTimeout(() => {
            obj.text = '456'
        }, 1000)

    </script>
</body>

</html>